from django.http import HttpResponse
from django.shortcuts import render_to_response
from web.ideas.models import Idea
from web.ideas.models import Comment
from web.tagging.models import *
from web.ideas.text import *
from datetime import datetime
from django.http import HttpResponseRedirect

def index (request):
    return HttpResponseRedirect('/ideas/home/')
    
def null (request):
    return HttpResponseRedirect('/ideas/')

def list (request):
    if validatePost(request.GET,['page']) == True:
        page = int(request.GET['page'])
    else:
        page = 1
    start = page*5 - 5
    ideas = Idea.objects.order_by('-change_date')[start:start+5]
    if len(ideas) == 0:
        return render_to_response('index.html', {'error_message': "There are no Ideas, idiot!"})
    count = Idea.objects.count()
    pages = count/5 + 1
    if count%5 == 0:
        pages = pages-1
    context = {'ideas': ideas, 'pages': pages, 'page': page}
    if page > 1:
        context['previous']=page-1
    if page < pages:
        context['next']=page+1
    return render_to_response('index.html', context)

def view(request, idea_title):
    ideas = Idea.objects.filter(title=idea_title)
    if len(ideas) == 0:
        return render_to_response('create.html', {'title': idea_title})
    else:    
        countComments = Comment.objects.filter(idea=ideas[0]).count()
        return render_to_response('view.html', {'texto': ideas[0].text ,'idea': ideas[0], 'count': countComments})
        
        
def create(request, idea_title):
    if validatePost(request.POST,['author', 'text', 'tags']) == False:
        error_message = "Author, text and at least one tag are required fields"
        return render_to_response('create.html', {'title': idea_title, 'error_message': error_message})
    
    ideas = Idea.objects.filter(title=idea_title)
    
    if len(ideas) == 0:
        i = Idea(author=request.POST['author'], tags=request.POST['tags'],
                 title=idea_title, text=request.POST['text'],
                 pub_date=datetime.now(), change_date=datetime.now())
        i.save()
        
    return HttpResponseRedirect('/ideas/%s/' % idea_title)
    
def remove(request, idea_title):
        ideas = Idea.objects.filter(title=idea_title)
        if len(ideas) == 0:
            return render_to_response('edit.html', {'error_message': "Idea doesn't exist!"})
        ideas[0].delete()
        return HttpResponseRedirect('/ideas/')

def edit(request, idea_title):  
    ideas = Idea.objects.filter(title=idea_title)
    
    if len(ideas) == 0:
        return render_to_response('edit.html', {'error_message': "Idea doesn't exist!"})
    idea = ideas[0]
    
    if len(request.POST) == 0:
        return render_to_response('edit.html', {'idea': idea})
    else:
        if validatePost(request.POST,['text', 'title']) == False:
            error_message = "Title and text are required fields"
            return render_to_response('edit.html', {'idea': idea, 'error_message': error_message})
        
        exists = Idea.objects.filter(title=request.POST['title'])
        if exists[0].title == idea_title:
            idea.text = request.POST['text']
            idea.title = request.POST['title']
            idea.tags = request.POST['tags']
            idea.change_date = datetime.now()
            idea.save()
            return HttpResponseRedirect('/ideas/%s/' % idea.title)
        else:
            return render_to_response('edit.html', {'idea': idea, 'error_message': 'Idea '+request.POST['title']+' already exists'})
        
def comments(request, idea_title):
    ideas = Idea.objects.filter(title=idea_title)
    
    if len(ideas) == 0:
        return render_to_response('edit.html', {'error_message': "Idea doesn't exist!"})
    else:
        idea = ideas[0]
        lastComments = Comment.objects.filter(idea=idea).order_by('-pub_date')[:10]
        if len(request.POST) > 0:
            if validatePost(request.POST,['text', 'title']) == False:
                error_message = "Title and text are required fields"
                return render_to_response('comments.html', {'comments' : lastComments, 'idea': idea, 'error_message': error_message})
            c = Comment(title=request.POST['title'], text=request.POST['text'],
                 pub_date=datetime.now(), idea=idea)
            c.save()
        
        return render_to_response('comments.html', {'idea':idea, 'comments' : lastComments})
    
def latestComments(request):
    comments = Comment.objects.order_by('-pub_date')[:10]
    return render_to_response('latestComments.html', {'comments' : comments})

def search(request):
    if validatePost(request.POST,['searchsite']) == False:
        return render_to_response('search.html', {'error_message': "Please search for something"})
    ideas = Idea.objects.filter(title__icontains=request.POST['searchsite'])
    tags = Tag.objects.usage_for_model(Idea, counts=True).filter(name__icontains=request.POST['searchsite'])
    if len(ideas) == 0 and len(tags) == 0:
        return render_to_response('search.html', {'error_message': "No ideas or tags found", 'create': request.POST['searchsite']})
    return render_to_response('search.html', {'ideas': ideas, 'tags': tags, 'create': request.POST['searchsite']})
    
def viewTag(request, tag_name):
    try:
        tag = Tag.objects.get(name=tag_name)
    except Tag.DoesNotExist:
        return HttpResponseRedirect('/ideas/')
    
    ideas = TaggedItem.objects.get_by_model(Idea, tag)
    return render_to_response('tags.html', {'ideas': ideas, 'tag': tag_name})

def tagCloud(request):
    tags = Tag.objects.cloud_for_model(Idea, steps=30)[:100]
    for tag in tags:
        tag.font_size += 20
    return render_to_response('cloud.html', {'tags': tags})

